import type { ITjFormItemProps } from '@/tjComponents/TjForm/TjFormItem';
import { Cascader, DatePicker, Input, Select } from 'antd';
import type { FormInstance } from 'antd';
import type { CascaderOptionType, CascaderValueType } from 'antd/lib/cascader';
import _ from 'lodash';

const { Option } = Select;

// 保留两位小数
const keepTwoDecimalPlaces = /^([0-9]{1}|^[1-9]{1}\d{1,15})(\.\d{1,2})?$/;

// 补贴单价、结算单价
const unitPrice = /^(?:[1-9]\d{0,2}(?:\.\d{1,2})?|0\.\d{1,2}|1000(?:\.0{1,2})?|0)$/;

// 结算单价
const settlementUnitPrice =
  /^(?:[1-9]\d{0,2}(?:\.\d{1,2})?|0\.\d{1,2}|1\d{3}(?:\.\d{1,2})?|2000(?:\.0{1,2})?|0)$/;

// 结算电量、保留三位小数
const keeptThreeDecimalPlaces = /^-?(?!0\d)\d{1,10}(\.\d{1,3})?$/;

// 保留两位小数可为负
const keepTwoDecimalPlaces2 = /^-?(?!0\d)\d{1,10}(\.\d{1,2})?$/;

// 结算单价
const statementPrice = /^-?(?!0\d)\d{1,10}(\.\d{1,2})?$/;

const settlementStatus = [
  {
    label: '正常结算',
    value: 1,
  },
];

/**
 * 生成表单项
 * @param {object} optionsData - 交易单元、合同时段选项数据
 * @param {boolean} disabled - 是否禁用
 * @param {function} changeStationId - 选择交易单元回调
 * @returns {ITjFormItemProps[]} - 表单项配置
 */
const formItems = (
  optionsData: any,
  disabled: boolean,
  changeStationId: (value: CascaderValueType, selectedOptions?: CascaderOptionType[]) => void,
  form: FormInstance<any>,
): ITjFormItemProps[] => {
  const marketId = _.get(optionsData, 'marketId', []);
  const marketingUnit = _.get(optionsData, 'marketingUnit', []);
  const contractTimeFrame = _.get(optionsData, 'contractTimeFrame', []);
  const items: ITjFormItemProps[] = [
    {
      name: 'stationId',
      label: '交易单元',
      render: (
        <Cascader
          options={marketingUnit?.filter((v: any) => v.marketId === marketId)}
          placeholder="请选择交易单元"
          onChange={(value: CascaderValueType, selectedOptions?: CascaderOptionType[]) =>
            changeStationId(value, selectedOptions)
          }
        />
      ),
      rules: [{ required: true, message: '请选择交易单元' }],
    },
  ];

  if (marketId === 'PDBLJ') {
    // 黑龙江
    items.push(
      ...[
        {
          name: 'statementSubjectCode',
          label: '结算科目编码',
          required: true,
          rules: [
            // { required: true, message: '请输入结算科目编码' },
            { pattern: /^[A-Za-z0-9]+$/, message: '只能输入字母和数字' },
            {
              validator: (_: any, value: any) => {
                const stationId = form.getFieldValue('stationId');
                if (stationId && stationId.length > 1) {
                  const first = stationId[0];
                  if (first === 'GXCSG' || first === 'PXBMX') {
                    return Promise.resolve();
                  } else {
                    if (value) {
                      return Promise.resolve();
                    } else {
                      return Promise.reject(new Error('请输入结算科目编码'));
                    }
                  }
                } else {
                  return Promise.resolve();
                }
              },
            },
          ],
        },
        {
          name: 'statementSubjectName',
          label: '结算科目',
          rules: [{ required: true, message: '请输入结算科目' }],
        },
        { name: 'contractSequence', label: '合同序列' },
        { name: 'contractName', label: '合同名称' },
        { name: 'stationObject', label: '结算对象' },
        {
          name: 'contractPeriod',
          label: '合同时段',
          render: (
            <Select>
              {contractTimeFrame.length > 0 &&
                contractTimeFrame.map((v: any) => <Option value={v.value}>{v.title}</Option>)}
            </Select>
          ),
        },
        {
          name: 'planContractElectricity',
          label: '交易计划电量/合同电量',
          rules: [
            { pattern: keeptThreeDecimalPlaces, message: '请输入正确数字范围且只保留三位小数' },
          ],
        },
        {
          name: 'settlementElectricityCapacity',
          label: '结算电量/容量',
          rules: [
            { required: true, message: '请输入结算电量/容量' },
            { pattern: keeptThreeDecimalPlaces, message: '请输入正确数字范围且只保留三位小数' },
          ],
        },
        {
          name: 'statementPrice',
          label: '结算电价',
          rules: [
            { pattern: keeptThreeDecimalPlaces, message: '请输入正确数字范围且只保留三位小数' },
          ],
        },
        {
          name: 'statementCost',
          label: '结算电费',
          rules: [
            { required: true, message: '请输入结算电费' },
            { pattern: keepTwoDecimalPlaces2, message: '请输入正确金额且只保留两位小数' },
          ],
        },
        {
          name: 'statementMonth',
          label: '结算月份',
          render: <DatePicker picker="month" format={'YYYY-MM'} style={{ width: '100%' }} />,
          rules: [{ required: true, message: '请选择结算月份' }],
        },
        {
          name: 'remark',
          label: '备注',
          rules: [{ max: 50, message: '输入内容不能超过50个字符' }],
          col: {
            span: 24,
          },
        },
      ],
    );
  } else if (marketId === 'PXBSX') {
    // 陕西
    items.push(
      ...[
        {
          name: 'statementSubjectCode',
          label: '结算科目编码',
          required: true,
          rules: [
            // { required: true, message: '请输入结算科目编码' },
            { pattern: /^[A-Za-z0-9]+$/, message: '只能输入字母和数字' },
            {
              validator: (_: any, value: any) => {
                const stationId = form.getFieldValue('stationId');
                if (stationId && stationId.length > 1) {
                  const first = stationId[0];
                  if (first === 'GXCSG' || first === 'PXBMX') {
                    return Promise.resolve();
                  } else {
                    if (value) {
                      return Promise.resolve();
                    } else {
                      return Promise.reject(new Error('请输入结算科目编码'));
                    }
                  }
                } else {
                  return Promise.resolve();
                }
              },
            },
          ],
        },
        {
          name: 'statementSubjectName',
          label: '结算科目',
          rules: [{ required: true, message: '请输入结算科目' }],
        },
        { name: 'contractSequence', label: '合同序列' },
        { name: 'contractName', label: '合同名称' },
        {
          name: 'planContractElectricity',
          label: '合同电量',
          rules: [
            { pattern: keeptThreeDecimalPlaces, message: '请输入正确数字范围且只保留三位小数' },
          ],
        },
        {
          name: 'settlementElectricityCapacity',
          label: '结算电量(MWh)',
          rules: [
            { required: true, message: '请输入结算电量' },
            { pattern: keeptThreeDecimalPlaces, message: '请输入正确数字范围且只保留三位小数' },
          ],
        },
        {
          name: 'statementPrice',
          label: '结算均价(元/MWh)',
          rules: [
            { pattern: keeptThreeDecimalPlaces, message: '请输入正确数字范围且只保留三位小数' },
          ],
        },
        {
          name: 'statementCost',
          label: '结算电费(元)',
          rules: [
            { required: true, message: '请输入结算电费' },
            { pattern: keepTwoDecimalPlaces2, message: '请输入正确金额且只保留两位小数' },
          ],
        },
        {
          name: 'statementUnitName',
          label: '结算单元',
          rules: [{ required: true, message: '请输入结算单元' }],
        },
        {
          name: 'adjustMonth',
          label: '调整月份',
          // render: <DatePicker picker="month" format={'YYYY-MM'} style={{ width: '100%' }} />,
          // rules: [{ required: true, message: '请选择调整月份' }],
        },
        {
          name: 'statementMonth',
          label: '结算月份',
          render: <DatePicker picker="month" format={'YYYY-MM'} style={{ width: '100%' }} />,
          rules: [{ required: true, message: '请选择结算月份' }],
        },
        {
          name: 'remark',
          label: '备注',
          rules: [{ max: 50, message: '输入内容不能超过50个字符' }],
          col: {
            span: 24,
          },
        },
      ],
    );
  } else {
    // 山西、其他
    items.push(
      ...[
        {
          name: 'statementCode',
          label: '结算编号',
          required: true,
          rules: [
            // { required: true, message: '请输入结算编号' },
            // { pattern: /^[0-9]*[1-9][0-9]*$/, message: '只能输入数字' },
            { pattern: /^[A-Za-z0-9]+$/, message: '只能输入字母和数字' },
            {
              validator: (_: any, value: any) => {
                const stationId = form.getFieldValue('stationId');
                if (stationId && stationId.length > 1) {
                  const first = stationId[0];
                  if (first === 'GXCSG' || first === 'PXBMX') {
                    return Promise.resolve();
                  } else {
                    if (value) {
                      return Promise.resolve();
                    } else {
                      return Promise.reject(new Error('请输入结算编号'));
                    }
                  }
                } else {
                  return Promise.resolve();
                }
              },
            },
          ],
        },
        { name: 'statementTypeName', label: '结算类型' },
        {
          name: 'statementPrice',
          label: '结算单价（元/MWh）',
          rules: [
            {
              pattern: statementPrice,
              message: '只能输入数字范围（保留小数点后2位）',
            },
          ],
        },
        {
          name: 'statementSubsidyPrice',
          label: '补贴单价（元/MWh）',
          rules: [
            {
              pattern: unitPrice,
              message: '只能输入数字范围0-1000（保留小数点后2位）',
            },
          ],
          render: <Input disabled />,
        },
        {
          name: 'statementQuantity',
          label: '结算电量（MWh）',
          rules: [
            { required: true, message: '请输入结算电量' },
            { pattern: keeptThreeDecimalPlaces, message: '请输入正确数字范围且只保留三位小数' },
          ],
        },
        {
          name: 'statementCost',
          label: '结算电费（元）',
          rules: [
            { required: true, message: '请输入结算电费' },
            { pattern: keepTwoDecimalPlaces2, message: '请输入正确金额且只保留两位小数' },
          ],
        },
        {
          name: 'contractTimeFrame',
          label: '合同时段',
          render: (
            <Select>
              {contractTimeFrame.length > 0 &&
                contractTimeFrame.map((v: any) => <Option value={v.value}>{v.title}</Option>)}
            </Select>
          ),
        },
        {
          name: 'statementSubsidyIncome',
          label: '补贴结算收入（元）',
          render: <Input disabled />,
          // rules: [{ pattern: keepTwoDecimalPlaces2, message: '请输入正确金额且只保留两位小数' }],
        },
        {
          name: 'statementOtherCost',
          label: '其他结算费用（元）',
          rules: [
            { required: true, message: '请输入其他结算费用' },
            { pattern: keepTwoDecimalPlaces2, message: '请输入正确金额且只保留两位小数' },
          ],
        },
        {
          name: 'statementEnergyIncome',
          label: '总结算收入-不含补贴（元）',
          rules: [
            // { required: true, message: '请输入总结算收入' },
            // { pattern: keepTwoDecimalPlaces2, message: '请输入正确金额且只保留两位小数' },
          ],
          render: <Input disabled />,
        },
        {
          name: 'statementTotalIncome',
          label: '总结算收入-含补贴（元）',
          rules: [
            // { required: true, message: '请输入总结算收入' },
            // { pattern: keepTwoDecimalPlaces2, message: '请输入正确金额且只保留两位小数' },
          ],
          render: <Input disabled />,
        },
        {
          name: 'status',
          label: '结算状态',
          render: <Select options={settlementStatus} disabled />,
        },
        {
          name: 'statementMonth',
          label: '结算月份',
          render: <DatePicker picker="month" format={'YYYY-MM'} style={{ width: '100%' }} />,
          rules: [{ required: true, message: '请选择结算月份' }],
        },
        {
          name: 'taxRate',
          label: '增值税率（%）',
          rules: [{ pattern: keepTwoDecimalPlaces, message: '请输入正确数字范围且只保留两位小数' }],
        },
        {
          name: 'remark',
          label: '备注',
          rules: [{ max: 50, message: '输入内容不能超过50个字符' }],
          col: {
            span: 24,
          },
        },
      ],
    );
  }
  return items;
};

export { formItems, settlementStatus };
